import React, { useState, useEffect, useRef } from 'react';

export const useParams = () => {
  const [paramsRes, setParamsRes] = useState<Record<string, string>>({});
  const latestParamsRef = useRef(paramsRes); // 用于保存最新的 paramsRes 引用
  latestParamsRef.current = paramsRes;

  useEffect(() => {
    const newParams: Record<string, string> = {};
    const hash = window.location.hash;
    const splitArr = hash.split('?');
    if (splitArr.length > 1) {
      const [route, params] = splitArr;
      const otherParams = params.split('&');
      for (const param of otherParams) {
        const [key, value] = param.split('=');
        if (key && value) {
          newParams[key] = decodeURIComponent(value);
        }
      }
    }
    setParamsRes(newParams); // 使用新的参数对象更新 state
  }, []); // 依赖数组为空，这意味着 useEffect 只会在组件挂载时运行一次

  useEffect(() => {
    const handleHashChange = () => {
      const newParams: Record<string, string> = {};
      const hash = window.location.hash;
      const splitArr = hash.split('?');
      if (splitArr.length > 1) {
        const [route, params] = splitArr;
        const otherParams = params.split('&');
        for (const param of otherParams) {
          const [key, value] = param.split('=');
          if (key && value) {
            newParams[key] = decodeURIComponent(value);
          }
        }
      }
      latestParamsRef.current = newParams;
      setParamsRes(latestParamsRef.current); // 使用最新的 paramsRes 更新 state
    };

    // 添加事件监听器以侦听 hash 变化
    window.addEventListener('hashchange', handleHashChange);

    // 清理函数
    return () => {
      window.removeEventListener('hashchange', handleHashChange);
    };
  }, []);

  return paramsRes;
};